-- 获取参数
local goodsId = KEYS[1]
local userId = KEYS[2]
local num = tonumber(ARGV[1])

-- 定义key
local stockKey = "seckill:goods:stock:" .. goodsId
local userQuotaKey = "seckill:user:quota:" .. userId .. ":" .. goodsId
local globalQuotaKey = "seckill:global:quota:" .. goodsId

-- 获取当前值
local stock = tonumber(redis.call('get', stockKey))
local userQuota = tonumber(redis.call('get', userQuotaKey))
local globalQuota = tonumber(redis.call('get', globalQuotaKey))

-- 如果值不存在，返回-1
if not stock then return -1 end
if not userQuota then userQuota = 10 end
if not globalQuota then globalQuota = -1 end

-- 检查库存和限额
if stock < num then return -2 end
if userQuota < num then return -3 end
if globalQuota ~= -1 and globalQuota < num then return -4 end

-- 更新值
redis.call('decrby', stockKey, num)
redis.call('decrby', userQuotaKey, num)
if globalQuota ~= -1 then
    redis.call('decrby', globalQuotaKey, num)
end

-- 返回成功
return 1 